/**
 * Author: QKL Wecaht: qklandy, QQ: 80508567
 * Date: 2015/7/22
 * Time: 15:20
 */
!(function(window,$) {

    var console = window.console || {log:function(){}};

    //参数
    var error = {
            240: "请输入常用邮箱地址",
            210: "请输入100字以内的邮箱地址",
            220: "请输入有效的邮箱地址，如：user@duigoujob.com",
            241: "请输入密码",
            211: "请输入6-16位密码，字母区分大小写",
            299: "您操作太频繁了,过一会儿再来吧!",
            400: "该帐号不存在或密码错误，请重新输入",
            401: "登录失败，该帐号已被禁用",
            500: "登录失败,系统内部异常",
            other: "网络异常，请刷新重试"
        }
    //公用函数工具
    var Common={
        /**
         * 动态加载js或css
         * @param path  相对根目录的路径或当前的文档相对路径  可网址
         * @param fn    加载完成调用函数
         * @returns {Common}
         */
        use: function(path, callback){
            var i = 0, head = $('head')[0];
            var path = path.replace(/\s/g, '');
            var iscss = /\.css$/.test(path);
            var node = document.createElement(iscss ? 'link' : 'script');
            var id = '_duigoujob_' + path.replace(/\.|\//g, '');
            if(iscss){ node.rel = 'stylesheet';}
            node[iscss ? 'href' : 'src'] = /^http:\/\//.test(path) ? path : path;
            node.id = id;
            if(!$('#'+ id)[0]){
                head.appendChild(node);
            }
            //轮询加载就绪
            if(callback){
                //if(document.all){
                //    $(node).ready(callback);
                //} else {
                //    $(node).load(callback);
                //}
                $(node).load(callback);
            }
        },

        isReady: function(plugin){
            var msg='你还未引入'+plugin+'或未加载完成'+plugin;
            if(!$(document.createElement('div'))[plugin]){
                console.log(msg);
                return false;
            } else {
                return true;
            }
        },

        /**
         * 换行换成br
         * @param str
         * @param is_xhtml
         * @returns {string}
         */
        nl2br: function(str, is_xhtml) {
            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
        },

        /**
         *通用的上传方法
         * @targetInput     上传的出发事件源
         * @targetUrl       上传的服务端处理程序
         * @success         上传成功的调用函数
         * @fail            上传失败的调用函数
         * @upType          用于分类的上传类型
         * @doms            array('')
        **/
        upload: function uploadImg( triggerInput, targetUrl, success, fail, upType, doms ) {
            if(!Common.isReady('Jcrop')){
                return ;
            }
            $(doms['cropbox']).html('<img data-src="" id="target">');
            targetInput = $( triggerInput );
            var inputId = targetInput.attr( 'id' );
            var hint = targetInput.attr( 'title' );

            var dataType = 'json';
            $('#uptype').val(upType);
            var params = { type: upType};
            var previewbox=[150,150];
            var updatePreview=function(c){
                if (parseInt(c.w) > 0) {
                    var rx = previewbox[0] / c.w;
                    var ry = previewbox[1] / c.h;

                    $(doms['preview']).css({
                        width: Math.round(rx * boundx) + 'px',
                        height: Math.round(ry * boundy) + 'px',
                        marginLeft: '-' + Math.round(rx * c.x) + 'px',
                        marginTop: '-' + Math.round(ry * c.y) + 'px'
                    });

                    //set form
                    $('#x1').val(c.x);
                    $('#x2').val(c.x2);
                    $('#y1').val(c.y);
                    $('#y2').val(c.y2);
                    $('#w').val(c.w);
                    $('#h').val(c.h);
                }
            };

            if(!!targetInput[0].files && !!targetInput[0].files[0].size){
                if(targetInput[0].files[0].size >  1048576*3){
                    alert( hint );
                    $("input[type = 'file']").val("");
                    return ;
                }
            }

            this.AllowExt = '.jpg,.gif,.jpeg,.png,.pjpeg,.bmp';
            this.FileExt = targetInput.val().substr(targetInput.val().lastIndexOf(".")).toLowerCase();
            if(this.AllowExt != 0 && this.AllowExt.indexOf(this.FileExt) == -1)//judge file format
            {
                alert( hint );
                $("input[type = 'file']").val("");
            } else {
                $.ajaxFileUpload ({
                    url: targetUrl,
                    secureuri: false,
                    fileElementId: inputId,
                    data: params,
                    dataType: dataType,
                    // "content":{"srcImageW":650,"srcImageH":346,"uploadPath":"upload/workPic/d7f6a8cb0fd5473193a3ffd021a54838.png"}
                    success: function ( rs ) {
//                            console.log(rs);
//                            if ( dataType == 'text' )
//                        rs = $.parseJSON( rs );
                        if( rs.status ){
//                                success && success( rs.content, inputId );
//                                console.log(rs);
                            //裁剪
                            $newimg2=new Image();
                            $newimg2.onload=function(){
                                $(doms['cropbox']).find('.tip').hide();
                                boundx=$newimg2.width;
                                boundy=$newimg2.height;

                                !!doms['show'] && $(doms['show']).attr('src','/Uploads/'+rs.data.savepath+rs.data.savename);
                                !!doms['target'] && $(doms['target']).hide().attr('src','/Uploads/'+rs.data.savepath+rs.data.savename);
                                !!doms['input'] && $(doms['input']).val('/Uploads/'+rs.data.savepath+rs.data.savename);
                                !!doms['preview'] && $(doms['preview']).attr('src','/Uploads/'+rs.data.savepath+rs.data.savename);
                                jdata={
                                    boxWidth:200,
                                    boxHeight:200,
                                    minSelect:[10,10],
                                    setSelect: [ 10, 10, 100, 100 ],
                                    aspectRatio:!!doms['aspectRatio']?doms['aspectRatio']:1,
                                    onChange: updatePreview,
                                    onSelect: updatePreview
                                };
                                $bili=boundx/boundy;
                                if($bili>1){
                                    jdata.setSelect=[ 0, 0, boundy-1, boundy-1 ];
                                } else if($bili==1) {
                                    jdata.setSelect=[ 0, 0, 199, 199 ];
                                } else {
                                    jdata.setSelect=[ 0, 0, boundx-1, boundx-1 ];
                                }
                                $(doms['target']).Jcrop(jdata,function(){
                                    // Use the API to get the real image size
                                    var bounds = this.getBounds();
                                    boundx = bounds[0];
                                    boundy = bounds[1];
                                    // Store the API in the jcrop_api variable
                                    jcrop_api = this;

                                    // Move the preview into the jcrop container for css positioning
                                    //                        $('#preview-pane').appendTo(jcrop_api.ui.holder);
                                });

                                //小于200的居中
                                if(boundx/boundy>=1 && boundx<200){
                                    var marginLeft=(200-boundx)/2;
                                    var marginTop=(200-boundy)/2;
                                    $('.jcrop-holder').css({marginLeft:marginLeft+'px',marginTop:marginTop+'px'});
                                }
                                //end
                                //                        $('#target').show();
                            }
                            $newimg2.src='/Uploads/'+rs.data.savepath+rs.data.savename;
                            Common.popup({
                                type: 1,
                                title:false,
                                closeBtn:0,
                                area:['650px', '500px'],
                                skin:'layui-layer-nobg',
                                shadeClose:true,
                                content: $(doms['layer'])
                                },3);
                            //end
                        } else{
                            fail && fail( 1 );
                            alert( data.data);
                        }
                    },
                    error:function(data, status){
                        fail && fail( data );
                        alert( "上传失败，请重新上传, 可能是文件超过了3M");
                    }
                });
            }
        },


        detect: function(){
            var system = {
                win: false,
                mac: false,
                xll: false,
                ipad:false
            };
            //检测平台
            var p = navigator.platform;
            system.win = p.indexOf("Win") == 0;
            system.mac = p.indexOf("Mac") == 0;
            system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
            system.ipad = (navigator.userAgent.match(/iPad/i) != null)?true:false;

            var browser={
                versions:function(){
                    var u = navigator.userAgent, app = navigator.appVersion;
                    return {//移动终端浏览器版本信息
                        trident: u.indexOf('Trident') > -1, //IE内核
                        presto: u.indexOf('Presto') > -1, //opera内核
                        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                        mobile: !!u.match(/AppleWebKit.*Mobile.*/)||u.indexOf('iPad') > -1, //是否为移动终端
                        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                        iPad: u.indexOf('iPad') > -1, //是否iPad
                        webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
                    };
                }(),
                language:(navigator.browserLanguage || navigator.language).toLowerCase()
            }

            return {
                system:system,
                browser:browser
            }

            //if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
            //    if(window.location.href.indexOf("?mobile")<0){
            //        try{
            //            if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){
            //                window.location.href="http://shipei.qq.com/index.htm";
            //            }else if(/iPad/i.test(navigator.userAgent)){
            //
            //            }else{
            //                window.location.href="http://shipei.qq.com/simple/s/index/"
            //            }
            //        }catch(e){}
            //    }
            //}
            ////跳转语句，如果是手机访问就自动跳转到wap.baidu.com页面
            //if (system.win || system.mac || system.xll||system.ipad) {
            //    return system;
            //} else {
            //
            //}
        },

        //左侧导航栏的正则匹配生成新的url
        search:function(param,url,obj){
            var that=$(obj),type;
            if(!!param.parents){
                type=that.parents(param.parents).data(param.type);
            } else {
                type=that.data(param.type);
            }
            var reg=new RegExp(type+"=[a-z0-9_-]+?&",'i');
            url=url.replace(reg,type+'='+that.attr('href')+"&");
            window.location=url;
        },

        //去除搜索的条件
        trimSearch:function(param,url,obj){
            var that=$(obj),type;
            if(!!param.parents){
                type=that.parents(param.parents).data(param.type);
            } else {
                type=that.data(param.type);
            }
            if(type=='q'){
                var reg=new RegExp("q=.+?&",'i');
                url=url.replace(reg,'');
                //console.log(url);
                window.location=url;
                return ;
            }
            var reg=new RegExp(type+"=[a-z0-9_-]+?&",'i');
            url=url.replace(reg,type+'=ept&');
            window.location=url;
        },

        popup:function($myConfig,type){
            switch(type){
                case 1:case 3:{
                    //html
                    //{
                    //    type: 1,
                    //        title:false,
                    //    skin: 'layer-ext-moon', //'layui-layer-rim', //加上边框
                    //    shade:  $config['shade'], //[0],
                    //    shadeClose: $config['shadeClose'],//true,
                    //    area: $config['area'], //宽高
                    //    offset:$config['offset'],
                    //    content: $config['html'] =1
                    //    content: $('#wrap') =3
                    //}
                    $config= $.extend($myConfig,{type: 1});
                    layer.open($config);
                }break;
                case 2:{
                    //iframe
                    //var $config={
                    //    title:'title test',
                    //    closeBtn:0,
                    //    shade:0,
                    //    area:['340px', '215px'],
                    //    offset:'rb',
                    //    time:2000,
                    //    shift:2,
                    //    content:['test/guodu.html', 'no'],
                    //}
                    $config= $.extend($myConfig,{type: 2});
                    layer.open($config);
                }break;
                case 0:{
                    layer.msg($myConfig);
                }break;
            }

        }


    }

    //export to global window
    window.Common=Common;

    var Class = function(setings){
        var that = this;
        var config={

        }
        that.config = $.extend({}, that.config, setings);
    };

    Class.pt = Class.prototype;

    //默认配置
    Class.pt.config = {

    }


    //全局直接需要初始化的调用和注册事件
    $(function(){


        var tpl='     _       _\n'+
            '    | |     (_)\n'+
            '  __| |_   _ _  __ _  ___  _   _\n'+
            ' / _` | | | | |/ _` |/ _ \\| | | |\n'+
            '| (_| | |_| | | (_| | (_) | |_| |\n'+
            ' \\__,_|\\__,_|_|\__,  |\\___/ \\__,_|\n'+
            '                __/ |\n'+
            '               |___/            \n';

        $text='-------------------------------------\n'+
            '我们正在努力为大学生创造机会？\n'+
            '在这个蓬勃发展的互联网行业，我们正需要各界各行业的人才!\n'+
            '现在邀请你一同加入前行, 改变兼职行业, 快到碗里来！\n';


        if(console && console.log){
            console.log(tpl+$text);
            console.log('%c 请将简历发送至  qkl@duigoujob.com（ 邮件标题请以“姓名-应聘XX职位-来自console”命名）\n\n', 'color: #f00');
        }

        //是否有layer加载  如果加载就全局配置默认参数layer
        if(!!window.layer) {
            layer.config({
                skin:'layer-ext-moon',
                extend:'skin/moon/style.css'
            });
        }

        //公用的城市选择
        $('.location-hover').on('click',function(){
            var html='<div class="duigou-location-wrap">'
                        +'<div class="location-title"><i class="fa fa-map-marker"></i> 选择城市</div>'
                        +'<div class="location-content">'
                            +'<div class="hot-city">'
                                +'<dl class="clearfix">'
                                    +'<dt>热门城市</dt>'
                                    +'<dd><a href="/Home/Index/setCity/city/87">杭州</a></dd>'
                                    +'<dd><a href="/Home/Index/setCity/city/74">南京</a></dd>'
                                    +'<dd><a href="/Home/Index/setCity/city/1">北京</a></dd>'
                                    +'<dd><a href="/Home/Index/setCity/city/73">上海</a></dd>'
                                    +'<dd><a href="/Home/Index/setCity/city/169">武汉</a></dd>'
                                +'</dl>'
                            +'</div>'

                            //+'<div class="province"></div>'
                            //+'<div class="city"></div>'
                            //+'<div class="area"></div>'
                        +'</div>'
                    +'</div>';
            var config={
                title:false,
                shade: [0.35, '#000'],
                shadeClose: true,
                area:['650px', '160px'],
                offset: '100px',
                content:html,
            }
            if ($(window).width()>=720) {
                config.area=['650px', '160px'];
            } else {
                config.area=['80%', '160px'];
            }
            Common.popup(config,1);
        });

        //搜索框的兼职和公司 选项选择
        $('.search-tabs').hover(function(){
            var that=$(this);
            that.parent().addClass('over');
            that.addClass('over');
        },function(){
            var that=$(this);
            that.parent().removeClass('over');
            that.removeClass('over');
        });

        //$('.footer-wecaht').hover(function(){
        //        var that=$(this);
        //    },
        //    function(){
        //
        //    });

        //tooltip提示
       // $('[data-toggle="tooltip"]').tooltip();

        //dropdown 自定义下拉框
        $('.g-dropdown-wrap').on('click',function(){
            var that=$(this);
            that.find('.dropdown-lists-box').toggle();
        });

        //如果高度不够就给footer添加fixed
        if($('body').height()<=$(window).height()){
            $('.footer').css({position:'fixed',bottom:0});
        }

        //对勾样式的下拉
        if($('.dropdown-lists-box').size()>=1){
            $('.dropdown-lists-box li').on('click',function(){
                var that=$(this);
                var parent=that.closest('.dropdown-lists-box');
                if(!!parent.data('val')){
                    $(parent.data('val')).val(that.data('val'));
                    $(parent.data('val')).get(0).focus();
                    $(parent.data('val')).get(0).blur();
                }
                if(!!parent.data('show')){
                    $(parent.data('show')).val(that.data('show'));
                    $(parent.data('show')).get(0).focus();
                    $(parent.data('show')).get(0).blur();
                }
            });
        }
        //对勾 radio样式事件
        if($('.g-radio-wrap').size()>=1){
            $('.g-radio-wrap span').on('click',function(){
                var that=$(this);
                that.addClass('active').siblings('span').removeClass('active');
                var parent=that.closest('.g-radio-wrap');
                if(!!parent.data('val')){
                    $(parent.data('val')).val(that.data('val'));
                    $(parent.data('val')).get(0).focus();
                    $(parent.data('val')).get(0).blur();
                }
            });
        }

        //全局的搜索页面
        if($('.filter-item').size()>=1) {
            $('.filter-item .item a').on('click',function(e){
                Common.search({parents:'.filter-item',type:'type'},global.url,this);
                e.preventDefault();
            });
        }

        //搜索页面下的匹配生成新的url
        if($('.search-current-wrap').size()>=1) {
            $('.search-current-wrap a').on('click',function(e){
                Common.trimSearch({type:'type'},global.url,this);
                e.preventDefault();
            });
        }

        //滚动顶部
        $('#backtop').on('click',function(){
            $('html, body').animate({
                scrollTop: 0
            }, 180, 'linear');
        });
        $('#backtop').hide();
        $(window).scroll(function () {
            if ($(window).scrollTop() > 200) {
                $('#backtop').show();
            } else {
                $('#backtop').hide();
            }
        });

        //空闲时间和工作时间段的全局事件
        $('.g-times-wrap').not('.disabled').on('click','.g-time-select-all',function(e){
            var that=$(this);
            //默认事件 所有要去一次反
            if(!that.prop('checked')){
                //隐藏 去checked
                that.parent().find('i').addClass('remove');
                $('.g-times-wrap').find('.g-time-checkbox').prop('checked',false).siblings('i').addClass('remove');
            } else {
                that.parent().find('i').removeClass('remove');
                $('.g-times-wrap').find('.g-time-checkbox').prop('checked',true).siblings('i').removeClass('remove');
            }
        });
        $('.g-times-wrap').not('.disabled').on('click','.g-time-checkbox',function(e){
            var that=$(this);
            //默认事件 所有要去一次反
            if(!that.prop('checked')){
                that.parent().find('i').addClass('remove');
            } else {
                that.parent().find('i').removeClass('remove');
            }
        });

    });

})(this,jQuery);